package com.wsq.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import bindservice.BindService
import service.MyService

/**
 * service主要有两种启动方式：
 * 1.start
 * 2.bind
 *
 * 还有一种Service是IntentService
 *
 *
 */
class MainActivity : AppCompatActivity() {
    private lateinit var mService: BindService

    companion object{
        const val TAG = "Service"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startService()

    }

    override fun onStart() {
        super.onStart()

        Intent(this, BindService::class.java).also { intent ->
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onStop() {
        super.onStop()
        Intent(this, BindService::class.java).also {
            unbindService(connection)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService()
    }

    private val connection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as BindService.LocalBinder
            mService = binder.getService()

            Log.e(TAG, mService.getName())
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }


    /**
     * 以start的方式启动service
     */
    private fun startService(){
        var serviceIntent = Intent(MainActivity@this, MyService::class.java)
        serviceIntent.putExtra("key", "value")
//        var bundle = Bundle()
//        bundle.putString("key", "value")
//        startService(serviceIntent)
        //Android 9以上需要通过启动前台服务进行操作
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Log.e(TAG, "Android 9以上")
            startForegroundService(serviceIntent)
        }else{
            Log.e(TAG, "Android 9以下")
            startService(serviceIntent)
        }
    }

    private fun stopService(){
        var serviceIntent = Intent(MainActivity@this, MyService::class.java)

        stopService(serviceIntent)
    }

    private fun bindService(){

    }

    private fun unbindService(){

    }
}